package com.arr;

public class TestSortObj {

	public static void main(String args[]){
		Date[] dates = new Date[4]; 
		Date date1 = new Date(2017,4,19);
		Date date2 = new Date(2017,3,19);
		Date date3 = new Date(2015,2,11);
		Date date4 = new Date(2018,9,19);
		
		dates[0] = date1;
		dates[1] = date2;
		dates[2] = date3;
		dates[3] = date4;
		
		//System.out.println(date1.compare(date2));
		bubbleSort(dates);
		print(dates);
		Date date5 = new Date(2018,9,19);
		System.out.println(birnarySearch(dates,date5));
	}
	
	public static void bubbleSort(Date[] ds)
	{
		Date dTmp = new Date(0,0,0);
		for(int i = 0;i< ds.length;i++)
		{
			for(int j = 0;j< ds.length-i -1;j++)
			{
				if( (j+1) < ds.length && ds[j].compare(ds[j+1]) > 0)
				{
					dTmp = ds[j];
					ds[j] = ds[j+1];
					ds[j+1] = dTmp;
				}
			}
		}
	}
	
	public static void print(Date[] ds)
	{
		for(int i = 0;i<ds.length;i++)
		{
			System.out.println(i + "year:" +ds[i].year 
					+ "month:" +ds[i].month
					+ "day:" +ds[i].day);
		}
	}
	
	public static int birnarySearch(Date[] ds,Date d)
	{
		int start = 0;
		int end  = ds.length - 1;
		int mid = end / 2;
		
		while(start <= end)
		{
			if(d.compare(ds[mid]) == 0)
				return mid;
			else if(d.compare(ds[mid]) == 1)
			{
				start = mid + 1; 
			}
			else if(d.compare(ds[mid]) == -1)
			{
				end = mid - 1;
			}
			
			mid = (end + start) / 2;
		}
		return -1;
	}
}

class Date {
	int year,month,day;
	Date(int y,int m,int d) 
	{
		year = y;
		month = m;
		day = d;
	}
	
	public int compare(Date date) 
	{
		if(year == date.year && month == date.month
		&& day == date.day)
		{
			return 0;
		}
		
		if(year > date.year)
		{
			return 1;	
		}
		else if(month > date.month )
		{
			return 1;
		}
		else if(day > date.day)
		{
			return 1;
		}
		return -1;
    }
	
	public String toString()
	{
		return "";
	}
	
}
